package com.example.mongodb.mongodb.controller.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class RabbitmqDemo1Receiver {
    public static void main(String[] args) {

        String queueName = "ni.hao";


        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("123.207.179.78");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");

        try {
            Connection connection = connectionFactory.newConnection();
            Channel channel = connection.createChannel();
            /**
             * 声明一个队列
             * 参数说明：第一个参数：队列名称
             *          第二个参数：是否持久化
             *          第三个参数：是否排他
             *          第四个参数：是否自动删除
             *          第五个参数：属性值
             */
            channel.queueDeclare(queueName,false,false,false,null);
            String message  = "你好，世界";

            channel.basicPublish("",queueName,null,message.getBytes());

            //消息推送回调，消息推送成功后调用的方法
            DeliverCallback deliverCallback =(consumerTag,delivery)->{
              String msg = new String(delivery.getBody(),"UTF-8");
                System.out.println("[x] received "+msg);

            };

            /**
             * 1:队列名称
             * 2：true 只要服务器发送了就表示消息已经被消费者消费； false:服务端等待客户端显示的发送确认消息
             */
            channel.basicConsume(queueName,false,deliverCallback,consumerTag->{});


        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}
